package com.vimi8.ebb.manage;

import com.vimi8.ebb.dto.RegUserDto;
import com.vimi8.ebb.model.ElectricityBusiness;
import com.vimi8.ebb.model.RegUser;
import com.vimi8.ebb.service.ElectricityBusinessService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created by think on 2016/12/22.
 */
@Service
public class ElectricityBusinessManageImpl implements ElectricityBusinessManage {
    private Logger logger =  LoggerFactory.getLogger(this.getClass());
    @Autowired
    private ElectricityBusinessService electricityBusinessService;


    @Override
    public String registerElectricityBusiness(List<ElectricityBusiness> electricityBusinessList,String url) throws Exception{
        int count=0;
        try {
            List<RegUser> regUserList=new ArrayList<RegUser>();
            logger.info("electricityBusinessList="+electricityBusinessList+",url="+url);
            regUserList=swapRegUser(electricityBusinessList);
            logger.info("regUserList="+regUserList);
            String result = grantForElectricityBusiness(url, regUserList);
            logger.info("result count="+result);
          //  List<ElectricityBusiness> electricityBusinessList1=  swapElectricityBusiness(jsonArray,electricityBusinessList);
           // logger.info("electricityBusinessList1="+electricityBusinessList1);
           count= electricityBusinessService.batchRegisterElectricityBusiness(electricityBusinessList);
//            for(ElectricityBusiness electricityBusiness:electricityBusinessList1){
//                //regUserList.add(electricityBusiness.get);
//                count+=electricityBusinessService.registerElectricityBusiness(electricityBusiness);
//            }
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
        return count+"";
    }

    // 调用auth授权店铺管理员
    private String grantForElectricityBusiness(String url, List<RegUser> regUserList) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        logger.info("url param="+url);
        HttpPost httpost = new HttpPost(url);
        // headers: {
      //  httpost.addHeader("Content-Type","application/json");
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        RegUserDto regUserDto=new RegUserDto();
        JSONArray regUserJsonArray=new JSONArray();
        if(null!=regUserList){
             regUserJsonArray=  JSONArray.fromObject(regUserList);
        }

        logger.info("regUserJsonArray="+regUserJsonArray);
        nvps.add(new BasicNameValuePair("regUserListStr", regUserJsonArray.toString()));
        CloseableHttpResponse response = null;

        String resultEntity=null;
        String resultStr=null;
        JSONArray jsonArray=new JSONArray();
        try {
            httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
            response = httpclient.execute(httpost);
            HttpEntity entity = response.getEntity();
            resultEntity= EntityUtils.toString(entity);
            logger.info("result="+resultEntity);
            // {    “ret_code”:0,    “err_msg”:”ok”,    “result”:{“status”:0} }
            //返
            EntityUtils.consume(entity);
            JSONObject jsonObject=new JSONObject();
            if(!StringUtils.isEmpty(resultEntity)){
                jsonObject=JSONObject.fromObject(resultEntity);
            }
            if(jsonObject.containsKey("ret_code")){
                int retCode=jsonObject.optInt("ret_code");
                if(0==retCode){
                    resultStr= jsonObject.optString("result");
                }else{
                    String errorStr=jsonObject.optString("err_msg");
                    throw new Exception(errorStr);
                }
            }

        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
        return resultStr;
    }

    //把返回的RegUser  json数组转化为 ElectricityBusiness
    public List<ElectricityBusiness> swapElectricityBusiness(JSONArray jsonArray,List<ElectricityBusiness> electricityBusinessList){
        if(jsonArray==null||jsonArray.size()<=0){
            return null;
        }
        for(ElectricityBusiness electricityBusiness:electricityBusinessList){
            String mobileNo=electricityBusiness.getMobileNo();
            for(int i=0;i<jsonArray.size();i++){
                JSONObject jsonObject=jsonArray.getJSONObject(i);
                String mobileNoJSONObject=jsonObject.optString("phoneNumber");
                if(null!=jsonObject&&mobileNo.equals(mobileNoJSONObject)){
                    electricityBusiness.setId(jsonObject.optString("defaultClientId"));
                    break;
                }
            }
        }

        return electricityBusinessList;
    }
    //把ElectricityBusiness列表转为RegUser列表
    public List<RegUser> swapRegUser(List<ElectricityBusiness> electricityBusinessList){
        List<RegUser> regUsers=new ArrayList<>();
        /**
         * {
         "addressCode": "520206000000",
         "clientName": "江口县电商办",
         "clientOrgClass": "org_ebb_county",
         "nickName": "小勇",
         "orgName": "小勇电商办",
         "password": "123",
         "phoneNumber": "15628048759",
         "realName": "石勇",
         "userName": "jkxdsb"
         }
         * */
     for(ElectricityBusiness electricityBusiness:electricityBusinessList){
         RegUser regUser=new RegUser();
         String orgClass=null;
         //店铺组织类型
         regUser.setDefaultClientId(electricityBusiness.getId());
         regUser.setClientOrgClass("org_ebb_entity");
         regUser.setClientName(electricityBusiness.getStoreName());
         regUser.setAddressCode(electricityBusiness.getAddressCode());
         regUser.setAddressDetail(electricityBusiness.getAddressDetail());
         regUser.setNickName(electricityBusiness.getResponsiblePerson());
         regUser.setOrgName(electricityBusiness.getStoreName());
         regUser.setPhoneNumber(electricityBusiness.getMobileNo());
         regUser.setRealName(electricityBusiness.getResponsiblePerson());
         if(StringUtils.isEmpty(regUser.getPhoneNumber())){
             regUser.setUserName(UUID.randomUUID().toString());
         }
         //regUser.setUserName(electricityBusiness.getResponsiblePerson());
         regUsers.add(regUser);
     }
        return regUsers;
    }
}
